package grape.wx.service.mp.user.impl;

import grape.base.rest.client.dict.DictClient;
import grape.base.service.dict.po.Dict;
import grape.common.service.common.dictenums.PublicDictEnums;
import grape.wx.service.mp.MpProperties;
import grape.wx.service.mp.user.po.MpUser;
import grape.wx.service.mp.user.mapper.MpUserMapper;
import grape.wx.service.mp.user.api.IMpUserService;
import grape.common.service.common.BaseServiceImpl;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 公众号微信用户表 服务实现类
 * </p>
 *
 * @author yangwei
 * @since 2020-07-27
 */
@Service
public class MpUserServiceImpl extends BaseServiceImpl<MpUserMapper, MpUser> implements IMpUserService {

    @Autowired
    private DictClient dictClient;


    @Override
    public MpUser insert(WxMpUser wxMpUser, MpProperties.MpConfig mpConfig, MpUser.DictHowFrom dictHowFrom) {

        MpUser mpUserForInsert = new MpUser();
        mpUserForInsert = map(wxMpUser, mpUserForInsert, mpConfig);

        Dict dictByCode = dictClient.getDictByCode(dictHowFrom.name());
        mpUserForInsert.setHowFromDictId(dictByCode.getId());
        // 用户来源
        insert(mpUserForInsert);
        return mpUserForInsert;
    }

    @Override
    public MpUser updateById(WxMpUser wxMpUser, MpProperties.MpConfig mpConfig, MpUser mpUser) {
        assertNotNull(mpUser,"mpUser不能为空");
        assertParamNotEmpty(mpUser.getId(),"mpUser.id不能为空");
        mpUser = map(wxMpUser, mpUser, mpConfig);
        updateById(mpUser);
        return mpUser;
    }
    private MpUser map(WxMpUser wxMpUser,MpUser mpUser, MpProperties.MpConfig mpConfig) {
        mpUser.setAppCode(mpConfig.getAppCode());
        mpUser.setAppName(mpConfig.getAppName());

        mpUser.setIsSubscribe(wxMpUser.getSubscribe());
        mpUser.setOpenId(wxMpUser.getOpenId());


        mpUser.setAvatar(wxMpUser.getHeadImgUrl());
        mpUser.setNickname(wxMpUser.getNickname());
        mpUser.setCityName(wxMpUser.getCity());
        mpUser.setCountryName(wxMpUser.getCountry());
        String sex = wxMpUser.getSex().toString();
        // 1=男，2=女
        if(!isStrEmpty(sex)){
            if (isEqual("1",sex)) {
                Dict dictByCode = dictClient.getDictByCode(PublicDictEnums.DictGender.m.name());
                mpUser.setGenderDictId(dictByCode.getId());
            }else if (isEqual("2",sex)) {
                Dict dictByCode = dictClient.getDictByCode(PublicDictEnums.DictGender.f.name());
                mpUser.setGenderDictId(dictByCode.getId());
            }
        }

        mpUser.setProvinceName(wxMpUser.getProvince());
        mpUser.setUnionId(wxMpUser.getUnionId());

        return mpUser;
    }
}
